package com.mind.api.serivce;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.mind.api.WebServiceClient;
import com.mind.common.utils.StringUtils;
import com.mind.common.utils.spring.SpringUtils;
import com.mind.system.domain.SysConfig;
import com.mind.system.mapper.SysConfigMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;


public class TokenRefreshThread extends Thread {
    private static final Logger log = LoggerFactory.getLogger(TokenRefreshThread.class);
    private String username;
    private String password;
    private String baseUrl;
    private final ReentrantLock lock = new ReentrantLock();
    private String token;
    private SysConfigMapper sysConfigMapper;

    public TokenRefreshThread() {
        sysConfigMapper = SpringUtils.getBean("sysConfigMapper");
    }

    public void init() {
        SysConfig baseUrlConfig = sysConfigMapper.checkConfigKeyUnique("ITONGWEIBASEURL");
        if (baseUrlConfig != null && StringUtils.isNotBlank(baseUrlConfig.getConfigValue())) {
            baseUrl = baseUrlConfig.getConfigValue();
        }
        SysConfig usernameConfig = sysConfigMapper.checkConfigKeyUnique("ITONGWEIUSERNAME");
        if (baseUrlConfig != null && StringUtils.isNotBlank(usernameConfig.getConfigValue())) {
            username = usernameConfig.getConfigValue();
        }
        SysConfig passwordConfig = sysConfigMapper.checkConfigKeyUnique("ITONGWEIPASSWORD");
        if (passwordConfig != null && StringUtils.isNotBlank(passwordConfig.getConfigValue())) {
            password = passwordConfig.getConfigValue();
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                init();
                Map<String, String> params = new HashMap<>();
                params.put("username", username);
                params.put("password", password);
                WebServiceClient webServiceClient = new WebServiceClient();
                String body = webServiceClient.call(baseUrl + "/auth/createToken", JSON.toJSONString(params), null);
                log.info("通威 getToken result: {}", body);
                JSONObject jsonObject = JSONObject.parseObject(body);
                if (jsonObject != null && jsonObject.containsKey("code") && jsonObject.getInteger("code") == 200) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    token = "Bearer " + data.getString("access_token");
                    int expires_in = data.getInteger("expires_in");
                    // 等待过期时间
                    Thread.sleep((expires_in - 10) * 1000L);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // 重新设置中断状态
                log.error("Token refresh thread interrupted", e);
                break;
            } catch (Exception e) {
                log.error("Error refreshing token", e);
                try {
                    // 等待一段时间后重试
                    Thread.sleep(60000);
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    break;
                }
            }
        }
    }

    public String getToken() {
        return token;
    }

}
